#!/bin/bash

# test_frontend_api_fix.sh - 测试前端API数据解析修复
# 修复JavaScript Spread语法错误问题

echo "🔥 前端API数据解析修复验证脚本"
echo "================================================"

# 服务器信息
SERVER_URL="http://localhost:5700"
API_BASE="${SERVER_URL}/api"
FRONTEND_URL="${SERVER_URL}/web/"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 检查服务器状态
check_server() {
    echo -n "检查服务器状态... "
    if curl -s "$SERVER_URL/health" > /dev/null 2>&1; then
        echo -e "${GREEN}✅ 服务器运行正常${NC}"
        return 0
    else
        echo -e "${RED}❌ 服务器未运行${NC}"
        exit 1
    fi
}

# 测试API响应格式
test_api_response_format() {
    echo ""
    echo -e "${BLUE}🔗 测试API响应格式${NC}"
    echo "----------------------------------------"
    
    # 测试vehicles API
    echo -n "  测试vehicles API响应... "
    api_response=$(curl -s "$API_BASE/vehicles")
    
    # 检查是否为有效JSON
    if echo "$api_response" | jq . > /dev/null 2>&1; then
        echo -e "${GREEN}✅ JSON格式正确${NC}"
        
        # 检查响应结构
        has_code=$(echo "$api_response" | jq -r '.code' 2>/dev/null)
        has_data=$(echo "$api_response" | jq -r '.data' 2>/dev/null)
        has_total=$(echo "$api_response" | jq -r '.total' 2>/dev/null)
        
        echo "    响应结构分析:"
        echo "      code: $has_code"
        echo "      data: $(echo "$api_response" | jq -r '.data | type' 2>/dev/null)"
        echo "      total: $has_total"
        
        # 检查data是否为数组
        if echo "$api_response" | jq -e '.data | type == "array"' > /dev/null 2>&1; then
            echo -e "    ${GREEN}✅ data字段为数组类型${NC}"
            data_length=$(echo "$api_response" | jq -r '.data | length' 2>/dev/null)
            echo "      数组长度: $data_length"
        else
            echo -e "    ${RED}❌ data字段不是数组${NC}"
            return 1
        fi
        
    else
        echo -e "${RED}❌ 响应不是有效JSON${NC}"
        echo "    响应内容: $api_response"
        return 1
    fi
}

# 测试前端页面加载
test_frontend_loading() {
    echo ""
    echo -e "${BLUE}🌐 测试前端页面加载${NC}"
    echo "----------------------------------------"
    
    echo -n "  测试HTML页面访问... "
    if curl -s --head "$FRONTEND_URL" | grep -q "200 OK"; then
        echo -e "${GREEN}✅ 页面可访问${NC}"
    else
        echo -e "${RED}❌ 页面访问失败${NC}"
        return 1
    fi
    
    echo -n "  测试JavaScript文件加载... "
    main_js_url="${FRONTEND_URL}assets/js/main.js"
    if curl -s --head "$main_js_url" | grep -q "200 OK"; then
        echo -e "${GREEN}✅ main.js可加载${NC}"
    else
        echo -e "${RED}❌ main.js加载失败${NC}"
        return 1
    fi
    
    trim_js_url="${FRONTEND_URL}assets/js/trim.js"
    if curl -s --head "$trim_js_url" | grep -q "200 OK"; then
        echo -e "${GREEN}✅ trim.js可加载${NC}"
    else
        echo -e "${RED}❌ trim.js加载失败${NC}"
        return 1
    fi
}

# 检查JavaScript语法修复
check_js_syntax_fix() {
    echo ""
    echo -e "${BLUE}🔧 检查JavaScript语法修复${NC}"
    echo "----------------------------------------"
    
    # 检查main.js中的修复
    echo -n "  检查API数据解析修复... "
    if grep -q "data.data && Array.isArray(data.data)" "web/assets/js/main.js"; then
        echo -e "${GREEN}✅ API响应格式处理已修复${NC}"
    else
        echo -e "${RED}❌ API响应格式处理未修复${NC}"
        return 1
    fi
    
    echo -n "  检查数组展开语法保护... "
    if grep -q "AppState.vehicles ? \[\.\.\.AppState.vehicles\]" "web/assets/js/main.js"; then
        echo -e "${GREEN}✅ 数组展开语法保护已添加${NC}"
    else
        echo -e "${RED}❌ 数组展开语法保护缺失${NC}"
        return 1
    fi
    
    echo -n "  检查兼容性处理... "
    if grep -q "Array.isArray(data)" "web/assets/js/main.js"; then
        echo -e "${GREEN}✅ 向后兼容性处理已添加${NC}"
    else
        echo -e "${RED}❌ 向后兼容性处理缺失${NC}"
        return 1
    fi
}

# 模拟前端数据加载测试
simulate_frontend_data_loading() {
    echo ""
    echo -e "${BLUE}🧪 模拟前端数据加载测试${NC}"
    echo "----------------------------------------"
    
    # 获取API数据
    echo -n "  获取API数据... "
    api_data=$(curl -s "$API_BASE/vehicles")
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✅ API数据获取成功${NC}"
        
        # 使用jq模拟JavaScript数据处理
        echo -n "  模拟数据解析... "
        vehicles_array=$(echo "$api_data" | jq -r '.data // empty')
        
        if [ -n "$vehicles_array" ] && [ "$vehicles_array" != "null" ]; then
            vehicle_count=$(echo "$vehicles_array" | jq '. | length' 2>/dev/null || echo "0")
            echo -e "${GREEN}✅ 数据解析成功，找到 $vehicle_count 辆车辆${NC}"
            
            # 检查第一个车辆的数据结构
            if [ "$vehicle_count" -gt 0 ]; then
                echo "    第一辆车辆数据:"
                echo "$vehicles_array" | jq '.[0] | {make, model, price_from}' 2>/dev/null || echo "    数据解析失败"
            fi
        else
            echo -e "${RED}❌ 数据解析失败${NC}"
            return 1
        fi
    else
        echo -e "${RED}❌ API数据获取失败${NC}"
        return 1
    fi
}

# 生成测试报告
generate_test_report() {
    local total_tests="$1"
    local passed_tests="$2"
    local failed_tests="$3"
    
    echo ""
    echo "================================================"
    echo -e "${BLUE}📊 前端API修复测试报告${NC}"
    echo "================================================"
    echo "测试项目: $total_tests"
    echo -e "通过项目: ${GREEN}$passed_tests${NC}"
    echo -e "失败项目: ${RED}$failed_tests${NC}"
    
    if [ "$failed_tests" -eq 0 ]; then
        echo -e "${GREEN}🎉 前端API数据解析问题已修复！${NC}"
        echo ""
        echo "✅ API响应格式正确解析"
        echo "✅ JavaScript语法错误已修复"
        echo "✅ 数组展开语法保护已添加"
        echo "✅ 向后兼容性处理完善"
        echo "✅ 前端页面应该可以正常显示车辆数据"
        echo ""
        echo "🌐 请在浏览器中访问: $FRONTEND_URL"
        echo "🔍 按F12打开开发者工具检查Console输出"
    else
        echo -e "${RED}❌ 存在问题需要进一步修复${NC}"
        echo ""
        echo "建议检查:"
        echo "1. API响应格式是否符合预期"
        echo "2. JavaScript文件语法是否正确"
        echo "3. 浏览器Console是否还有错误信息"
    fi
    
    echo ""
    echo "💡 调试提示:"
    echo "   - API数据: curl $API_BASE/vehicles | jq ."
    echo "   - 前端页面: $FRONTEND_URL"
    echo "   - 开发者工具: F12 → Console"
}

# 主测试流程
main() {
    echo "开始测试时间: $(date)"
    echo ""
    
    # 检查服务器
    check_server
    
    # 初始化计数器
    total_tests=0
    passed_tests=0
    failed_tests=0
    
    # 运行测试项目
    tests=(
        "test_api_response_format"
        "test_frontend_loading"
        "check_js_syntax_fix"
        "simulate_frontend_data_loading"
    )
    
    for test in "${tests[@]}"; do
        ((total_tests++))
        
        if $test; then
            ((passed_tests++))
        else
            ((failed_tests++))
        fi
        
        sleep 0.5
    done
    
    # 生成报告
    generate_test_report "$total_tests" "$passed_tests" "$failed_tests"
    
    # 返回适当的退出码
    if [ "$failed_tests" -eq 0 ]; then
        exit 0
    else
        exit 1
    fi
}

# 运行主函数
main "$@"
